<template>
  <div id="userlist" class="template-page">
    <div class="tools">
      <el-form :model="form" class="form-input-m" label-width="80px" :inline="true">
        <el-form-item label="用户名">
          <el-input type="text" v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-button-group>
            <el-button @click="setStatus(1)">启用</el-button>
            <el-button @click="setStatus(0)">禁用</el-button>
            <el-button @click="setStatus('')">全部</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch()">查询</el-button>
          <el-button @click="handleClear()">清空</el-button>
          <el-divider direction="vertical" />
          <el-button type="primary" @click="addUser">新建用户</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table v-loading="loading" row-key="id" :data="userList" style="width: 100%" :height="conHeight">
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + (pageIndex - 1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="120" align="center">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handleEdit(scope.row.id)">{{ scope.row.username }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="realname" label="姓名" width="100" align="center"></el-table-column>
      <el-table-column prop="jobNum" label="工号" width="80" align="center"></el-table-column>
      <el-table-column prop="tel" label="电话" width="120" align="center"></el-table-column>
      <el-table-column label="角色" align="center">
        <template #default="scope">
          <template v-for="userRole in scope.row.UserRoles">{{ userRole.Role.roleName }}</template>
        </template>
      </el-table-column>
      <el-table-column label="所属机构">
        <template #default="scope">
          {{ scope.row.Organization ? scope.row.Organization.name : '' }}
        </template>
      </el-table-column>
      <el-table-column label="所属部门">
        <template #default="scope">
          <template v-for="(userDept, idx) in scope.row.UserDepts">{{ (userDept.Department ? userDept.Department.name : '') + (idx === scope.row.UserDepts.length - 1 ? '' : '/ ')}}</template>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          {{ formatStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <!-- 创建时间列 -->
      <el-table-column fixed="right" label="操作" width="160" align="center">
        <template #default="scope">
          <el-tooltip effect="dark" content="重置密码" placement="top">
            <el-button size="small" icon="Key" type="success" plain circle @click="handleResetPwd(scope.row.id, scope.row.UserRoles ? scope.row.UserRoles[0].roleId : '')"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button size="small" icon="EditPen" type="primary" plain circle @click="handleEdit(scope.row.id)"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button size="small" type="warning" icon="Delete" plain circle @click="handleDelete(scope.row.id)"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="禁用" placement="top" v-if="scope.row.status === 1">
            <el-button size="small" type="danger" icon="Lock" plain circle @click="handleLock(scope.row.id, 0, '禁用')"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="启用" placement="top" v-if="scope.row.status === 0">
            <el-button size="small" type="danger" icon="Unlock" plain circle @click="handleLock(scope.row.id, 1, '启用')"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom-page">
      <el-pagination :background="true" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageIndex" :page-sizes="pageSizeList" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"></el-pagination>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from 'vue';
import { pageSizes, notifyType, notifyMessage } from '../../utils/common';
import { AppStore } from '../../stores/store';
import { Encrypt } from '../../utils/crypto';
let conHeight = ref(
  (document.documentElement.clientHeight || document.body.clientHeight) - 148 + 'px'
);
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let pageSizeList = ref(pageSizes);
let pageSize = ref(pageSizes[0]);
let pageIndex = ref(1);
let totalCount = ref(0);
let loading = ref(false);
let userList: any = reactive([]);
let form = reactive({
  username: '',
  status: ''
});


findUserList();

function findUserList() {
  //查询搜索用户列表
  loading.value = true;
  userList.length = 0;
  const url = '/api/user/findUserList';
  proxy.$http
    .get(url, {
      params: {
        username: form.username,
        status: form.status,
        pageSize: pageSize.value,
        pageIndex: pageIndex.value
      }
    })
    .then((res: any) => {
      loading.value = false;
      if (res.status.code !== 1) {
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        userList.push(...res.data.list);
        totalCount.value = res.data.count;
      }
    })
    .catch((err: string) => {
      loading.value = false;
      notifyMessage(err, notifyType.warning, proxy);
    });
}
function setStatus(val: any) {
  form.status = val;
  findUserList();
}

function formatStatus(status: number) {
  switch (status) {
    case 0:
      return '禁用';
    case 1:
      return '启用';
    default:
      return '';
  }
}

//点击每页数量
function handleSizeChange(val: number) {
  pageSize.value = val;
  pageIndex.value = 1;
  findUserList();
}

//点击跳转页码
function handleCurrentChange(val: number) {
  pageIndex.value = val;
  findUserList();
}

//条件查询
function handleSearch() {
  pageIndex.value = 1;
  findUserList();
}

function handleClear() {
  form = {
    username: '',
    status: ''
  };
}

function addUser() {
  proxy.$router.push('/usersave');
}

function handleResetPwd(id: string, roleId: string) {
  let defaultPwd = '123456';
  if (store.sysDict && store.sysDict.defaultPwd) {
    defaultPwd = store.sysDict.defaultPwd;
  }
  proxy
    .$confirm('确定重置此用户的密码为初始密码为：' + defaultPwd, '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/user/changeDefaultPassword';
      proxy.$http
        .post(url, { id, defaultPwd: Encrypt(defaultPwd), roleId })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('重置初始密码成功', notifyType.success, proxy);
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}

//编辑
function handleEdit(id: string) {
  proxy.$router.push({ path: '/usersave', query: { id } });
}

//删除
function handleDelete(id: string) {
  proxy
    .$confirm('确定删除此用户?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/user/deleteUser';
      proxy.$http
        .post(url, { id })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage('删除成功', notifyType.success, proxy);
            findUserList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}

function handleLock(id: string, status: any, title: string) {
  proxy
    .$confirm('确定' + title + '此用户?', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/user/editUserSimple';
      proxy.$http
        .post(url, { id, status })
        .then((res: any) => {
          if (res.status.code === 1) {
            notifyMessage(title + '成功', notifyType.success, proxy);
            findUserList();
          } else {
            notifyMessage(res.status.msg, notifyType.warning, proxy);
          }
        })
        .catch((err: string) => {
          notifyMessage(err, notifyType.warning, proxy);
        });
    })
    .catch((err: string) => {
      console.log(err);
    });
}
</script>
<style lang="scss" scoped>
.tools {
  .el-form-item--default {
    margin-bottom: 0 !important;
  }
}
</style>
